package cn.zime.iot.view;

import cn.zime.iot.entity.User;
import cn.zime.iot.entity.UserDao;
import cn.zime.iot.handler.MainViewHandler;
import cn.zime.iot.req.StudentRequest;
import cn.zime.iot.res.TableDTO;
import cn.zime.iot.service.StudentService;
import cn.zime.iot.service.impl.StudentServiceImpl;
import cn.zime.iot.util.DBUtil;
import cn.zime.iot.view.ext.MainViewTable;
import cn.zime.iot.view.ext.MainViewTableModel;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.sql.Connection;
import java.util.Objects;


public class MainView extends JFrame {

    String userName;

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    JPanel northPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
    JButton addBtn = new JButton("增加");
    JButton updateBtn = new JButton("修改");
    JButton delBtn = new JButton("删除");
    JTextField searchTxt = new JTextField(15);
    JButton searchBtn = new JButton("查询");

    JPanel southPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
    JButton preBtn = new JButton("上一页");
    JButton nextBtn = new JButton("下一页");

    MainViewTable mainViewTable = new MainViewTable();
    private int pageNow = 1;
    private final int pageSize = 28; //一页显示多少条记录，28刚刚好
    private UserDao userDao = new UserDao();

    MainViewHandler mainViewHandler;

    public MainView() {
        super("ZIME·IoT2202学生成绩管理系统");
        Container contentPane = getContentPane();
        setBounds(100, 100, 1000, 1002);//高度不要改 1002刚刚好没有滚动条！！！


        mainViewHandler = new MainViewHandler(this);

        JMenuBar menuBar = new JMenuBar();
        setJMenuBar(menuBar);

        JMenu mnNewMenu = new JMenu("用户");
        menuBar.add(mnNewMenu);

        JMenuItem changePassword = new JMenuItem("修改密码");
        mnNewMenu.add(changePassword);
        changePassword.addActionListener(e -> new ChangePassword().setVisible(true));
        JMenuItem exit = new JMenuItem("退出登录");
        exit.addActionListener(e -> {
            dispose();
            new LoginView();
        });
        mnNewMenu.add(exit);
        JMenuItem cancelAccount = new JMenuItem("注销账号");
        mnNewMenu.add(cancelAccount);
        cancelAccount.addActionListener(e -> {
            int option = JOptionPane.showConfirmDialog(mainViewHandler.getMainView(), "你确认要将" + getUserName() + "注销吗？"
                    , "确认注销",
                    JOptionPane.YES_NO_OPTION);
            if (option == JOptionPane.YES_OPTION) {//确认
                //执行删除
                Connection con = null;

                User user = new User(getUserName());
                con = DBUtil.getConn();
                try {
                    int deleteNum = userDao.delete(con, user);
                    if (deleteNum == 1) {
                        JOptionPane.showMessageDialog(mainViewHandler.getMainView(), "注销成功");
                        dispose();
                        new LoginView();
                    } else {
                        JOptionPane.showMessageDialog(mainViewHandler.getMainView(), "删除失败");
                    }
                } catch (Exception e1) {
                    e1.printStackTrace();
                }

            }

        });

//        JMenu edit = new JMenu("编辑");
//        menuBar.add(edit);

        JMenu import_export = new JMenu("导入/导出");
        menuBar.add(import_export);

        JMenu about = new JMenu("关于");
        menuBar.add(about);
        JMenuItem importTo = new JMenuItem("从文件中导入数据");
        import_export.add(importTo);

        JMenuItem exportTo = new JMenuItem("将数据导出到文件");
        import_export.add(exportTo);

        JMenuItem aboutThis = new JMenuItem("关于本系统");
        aboutThis.addActionListener(e -> new AboutView());
        about.add(aboutThis);

        JPanel panel = new JPanel();
        panel.setBorder(new EmptyBorder(5, 5, 5, 5));

        //上中下三部分组件
        layoutNorth(contentPane);
        layoutCenter(contentPane);
        layoutSouth(contentPane);


        setIconImage(new ImageIcon(Objects.requireNonNull(MainView.class.getResource("/image/1.png"))).getImage());
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setResizable(false);
        setVisible(true);
    }

    private void layoutCenter(Container contentPane) {
        TableDTO dto = getTableDTO();
        MainViewTableModel mainViewTableModel = MainViewTableModel.assembleModel(dto.getData());
        // 把jTable和model关联
        mainViewTable.setModel(mainViewTableModel);
        mainViewTable.renderRule();
        JScrollPane jScrollPane = new JScrollPane(mainViewTable);
        contentPane.add(jScrollPane, BorderLayout.CENTER);
        showPreNext(dto.getTotalCount());
    }

    private TableDTO getTableDTO() {
        StudentService studentService = new StudentServiceImpl();
        StudentRequest request = new StudentRequest();
        request.setPageNow(pageNow);
        request.setPageSize(pageSize);
        request.setSearchKey(searchTxt.getText().trim());
        return studentService.retrieveStudents(request);
    }

    private void layoutSouth(Container contentPane) {
        preBtn.addActionListener(mainViewHandler);
        nextBtn.addActionListener(mainViewHandler);
        southPanel.add(preBtn);
        southPanel.add(nextBtn);
        contentPane.add(southPanel, BorderLayout.SOUTH);
    }

    /**
     * 设置上一页下一页是否可见
     */
    private void showPreNext(int totalCount) {
        preBtn.setVisible(pageNow != 1);
        int pageCount;
        if (totalCount % pageSize == 0) {
            pageCount = totalCount / pageSize;
        } else {
            pageCount = totalCount / pageSize + 1;
        }
        nextBtn.setVisible(pageNow != pageCount);
    }

    private void layoutNorth(Container contentPane) {
        // 增加事件监听
        addBtn.addActionListener(mainViewHandler);
        updateBtn.addActionListener(mainViewHandler);
        delBtn.addActionListener(mainViewHandler);
        searchBtn.addActionListener(mainViewHandler);
        northPanel.add(addBtn);
        northPanel.add(updateBtn);
        northPanel.add(delBtn);
        northPanel.add(searchTxt);
        northPanel.add(searchBtn);
        contentPane.add(northPanel, BorderLayout.NORTH);
    }


    public static void main(String[] args) {
        new MainView();
    }

    public void setPageNow(int pageNow) {
        this.pageNow = pageNow;
    }

    public int getPageNow() {
        return pageNow;
    }

    public void reloadTable() {
        TableDTO dto = getTableDTO();
        MainViewTableModel.updateModel(dto.getData());
        mainViewTable.renderRule();
        showPreNext(dto.getTotalCount());
    }

    public int[] getSelectedStudentIds() {
        int[] selectedRows = mainViewTable.getSelectedRows();
        int[] ids = new int[selectedRows.length];
        for (int i = 0; i < selectedRows.length; i++) {
            int rowIndex = selectedRows[i];
            Object idObj = mainViewTable.getValueAt(rowIndex, 0);
            ids[i] = Integer.parseInt(idObj.toString());
        }
        return ids;
    }
}
